package Other;

import java.util.List;
import DataConnectionInterface.*;
import Helper.*;

public class UniverseConcrete extends Pager implements Universe{

	private String name;
	private int ID;
	private List<ServerCard> cards = null;
	public static int entriesPerPage;

	public UniverseConcrete(String name, int ID) {
		
		this.name = name;
		this.ID = ID;
		
	}

	public UniverseConcrete(String name) {
		
		this.name = name;
		initUniverse();
	}

	private void initUniverse() {
		init(entriesPerPage);
	}

	public int getNumOfCards() {
		
		return cards.size();
	}

	public ServerCard getCard(int index) {
		
		return cards.get(index);
	}

	public void updateCard(ServerCard card, int index) {
		ConnectionPool pool = null;
		GameDataConnectionInterface con = null;
		try {
			if (cards.size() > index) {
				int characterID = cards.get(index).getID();
				pool = ConnectionPool.getInstance();
				con = pool.getConnection();
				con.updateCharacter(card, characterID);
				RefreshPage(con);
				pool.returnConnection(con);
			}
		} catch (GameException e) {
			if(pool != null && con != null)  pool.returnConnection(con);
		}
	}

	public void addCard(ServerCard card) {
		ConnectionPool pool = null;
		GameDataConnectionInterface con = null;
		try {
			pool = ConnectionPool.getInstance();
			con = pool.getConnection();
			con.insertCharacterToUniverse(card, ID);
			RefreshPage(con);
			pool.returnConnection(con);
		} catch (GameException e) {
			if(pool != null && con != null)  pool.returnConnection(con);
		}
	}

	public void removeCard(int index) {
		ConnectionPool pool = null;
		GameDataConnectionInterface con = null;
		try {
			if (cards.size() > index) {
				int characterID = cards.get(index).getID();
				pool = ConnectionPool.getInstance();
				con = pool.getConnection();
				con.deleteCharacter(characterID);
				RefreshPage(con);
				pool.returnConnection(con);
			}
		} catch (GameException e) {
			if(pool != null && con != null)  pool.returnConnection(con);
		}
	}

	public String getName() {
	
		return name;
	}

	public int getID() {
	
		return ID;
	}

	public void setID(int ID) {
	
		this.ID = ID;
	}


	public void loadCurrentPage() {
	
		try {
			ConnectionPool pool = ConnectionPool.getInstance();
			GameDataConnectionInterface con = pool.getConnection();
			RefreshPage(con);
			pool.returnConnection(con);
		} catch (GameException e) {
		}
	}

	// TODO: check boundaries
	protected void getNextPage(GameDataConnectionInterface con)
			throws GameException {
	
		List<ServerCard> tempList = con.getCardPage(ID, pageNumber + 1, entriesPerPage);
		if(tempList.size() == 0) return;
		cards = tempList;
		pageNumber++;
	}

	protected void getPreviousPage(GameDataConnectionInterface con)
			throws GameException {
	
		cards = con.getCardPage(ID, pageNumber - 1, entriesPerPage);
		pageNumber--;
	}

	protected void RefreshPage(GameDataConnectionInterface con)
			throws GameException {
	
		cards = con.getCardPage(ID, pageNumber, entriesPerPage);
	}

}
